<template>
	<el-container v-if="isAlready">
		<el-header style="padding-top: 0px;padding-bottom: 0px;height: 60px;">
			<div class="left-panel">
				<fsButton ref="button" plain size="default" :buttons="buttons" @clickHandler="buttonHandler"></fsButton>
			</div>
		</el-header>
		<el-main style="padding: 0px;padding-top: 3px;background-color: #fff;">
			<el-container>
				<el-header style="width: 98%;height: 60px;padding: 0px 15px;border: 1px rgba(0, 0, 0, .08) solid;
				margin-left: 1%;background-color: rgb(249, 249, 249);">
					<div class="left-panel" style="padding: 0px;width: 70%;">
						<div style="margin-left: -5px;float: left;">
							<img class="topblockimg" src="img/pandian-icon.png"/>
						</div>
						<label style="font-size: 14px;width: 70px;margin-top:0px;margin-left: 10px;">盘点任务</label>
						<sc-select-filter-check :data="filterData" :label-width="80" @on-change="tabChange">
						</sc-select-filter-check>
					</div>
					<div class="right-panel"  style="padding: 0px;width: 30%;">
						<ex-search v-if="searches" ref="search" :searches="searches" @searchOk="searchHandler" default-code="code" placeholder="请输入盘点单编码" :fixedParam="fixedParams"></ex-search>
					</div>
				</el-header>
				<el-main class="nopadding">
					<ex-table id="assetTable" ref="table" :columns="columns" :url="this.$API.asset.checkDocumentApi.page.url" :refs="this.$refs" search="search" @columnClick="columnClickHandler"
					:minheight="270"></ex-table>
				</el-main>
			</el-container>
		</el-main>
	</el-container>
	<edit-dialog ref="editDialog" @success="searchHandler"/>
	<change-check-user ref="changeCheckUser" @success="searchHandler"/>
</template>

<script>
import ExTable from "@/components/exTable/index.vue";
import ExSearch from "@/components/exSearch/index.vue";
import ExTreeNavigation from "@/components/exSearchTree/index.vue";
import ExSearchTree from "@/components/exSearchTree/index.vue";
import Selector from "@/components/exSelector/selecter.vue";
import scSelectFilterCheck from "@/components/scSelectFilterCheck/index.vue";
import useTabs from "@/utils/useTabs";
import router from "@/router";
import {uuid} from "@tinymce/tinymce-vue/lib/es2015/main/ts/Utils";
import editDialog from "@/views/asset/check/checkDocument/edit.vue";
import ChangeCheckUser from "@/views/asset/check/checkDocument/changeCheckUser.vue";
import {h} from "vue";
import ExLabel from "@/components/exLabel/index.vue";
import exStockLabel from "@/components/exStockLabel/index.vue";
import {ElContainer} from "element-plus";
import tool from "@/utils/tool";
import BaseTemplate from "@/utils/baseTemplate";

export default {
	name: '盘点单',
	components: {
		ChangeCheckUser,
		editDialog,
		scSelectFilterCheck,
		Selector,
		ExSearchTree,
		ExTreeNavigation,
		ExSearch,
		ExTable,
	},
	data() {
		return {
			dialog: {
				save: false,
				permission: false,
			},
			readDeptIds: this.$TOOL.current.readDeptIds(),
			manageDeptIds: this.$TOOL.current.manageDeptIds(),
			loginUser: tool.current.user(),
			isAlready: false,
			isManage: false,
			documentId:"",
			apiObj: [],
			ids:[],
			resultDatas: {},
			buttons: [],
			searches: null,
			columns: [
				// {code: "操作", name: "操作", width: "70",
				// 	click:[
				// 		{label:"编辑",icon:"el-icon-edit",event:'editDetail',type: "info", permission: ""},
				// 	]
				// },
				{code: "status", name: "盘点状态", width:"100",sortable: true,formatter:"DICT",key: "CHECK_DOCUMENT_STATUS"},
				{code: "code", name: "盘点单编码", width:"150",sortable:true},
				{code: "name", name: "盘点单名称", width:"300",click:"show1"},
				{code: "taskCode", name: "盘点任务编码", width:"160",sortable:true},
				// {code: "taskId", name: "盘点任务名称", width:"110",sortable:true, formatter: this.formatTaskName},
				{code: "taskType", name: "盘点单类型", width:"100", formatter:"DICT",key: "TASK_TYPE"},
				{code: "other.assetCount", name: "账有", width:"100",sortable:true},
				{code: "other.noDoCount", name: "未盘", width:"100",sortable:true},
				{code: "other.normalCount", name: "正常", width:"100",sortable:true},
				{code: "other.errCount", name: "异常", width:"100",sortable:true},
				{code: "other.surplusCount", name: "盘盈", width:"100",sortable:true},
				{code: "other.lossCount", name: "盘亏", width:"100",sortable:true},
				{code: "orgId", name: "盘点部门", width:"240",sortable:true,formatter: "DICT",key: "SysOrganization"},
				{code: "checkManageUsers", name: "管理人", width:"210",tooltiphide:true,formatter: function(row,value){
					//后端传过来是list，但是导出的时候数据类型是字符串，所以需要转换一下
					value = row.checkManageUser;
					let children = [];
					if(!value || value.length === 0){
						return null;
					}
					let userIds = value;
					if(Array.isArray(userIds)){
						children.push(h(exStockLabel, {key:row.id,code: 'SysUser',value:userIds,bool:true}));
						return h(ElContainer, {key:value,style: {display: 'flex'}}, () => children);
					}
					return null;
				}},
				{code: "checkUser", name: "盘点人", width:"220",tooltiphide:true,formatter: function(row,value){
					let children = [];
					if(!value){
						return null;
					}
					let userIds = value.split(",");
					if(Array.isArray(userIds)){
						//userIds.forEach(userId=>{
						//	children.push(h(ExLabel, {key:userId,code: 'SysUser',value:userId,bool:true}));
						//});
						children.push(h(exStockLabel, {key:row.id,code: 'SysUser',value:userIds,bool:true}));
						return h(ElContainer, {key:value,style: {display: 'flex'}}, () => children);
					}
					return null;
				}},
				{code: "createTime", name: "制定日期", width:"150",formatter: "DATE"},
				{code: "startDate", name: "开始日期", width:"150",formatter: "DATE"},
				{code: "endDate", name: "结束日期", width:"150",formatter: "DATE"},
				{code: "finishDate", name: "完成日期", width:"150",formatter: "DATE"},
			],
			filterData: [
				{
					title: "【任务状态】",
					key: "status",
					multiple: false,
					options: [{
						label: "全部(0)",
						value: ""
					},
						{
							label: "未盘(0)",
							value: "0"
						},
						{
							label: "盘点中(0)",
							value: "1"
						},
						{
							label: "盘点结束(0)",
							value: "2"
						},
					]
				},
				{
					title: "【盘点结果】",
					key: "checkResult",
					multiple: false,
					options: [
						{
						label: "全部(0)",
						value: ""
					},
						{
							label: "未盘(0)",
							value: "noDoCount"
						},
						{
							label: "正常(0)",
							value: "normalCount"
						},
						{
							label: "异常(0)",
							value: "errCount"
						},
						{
							label: "盘盈(0)",
							value: "surplusCount"
						},
						{
							label: "盘亏(0)",
							value: "lossCount"
						},
					]
				},
			],
			documentStatus:"",
			checkResult:"",
			parentLevelCode:"",
			fixedParams: {
			},
			taskName:'',
			taskStatus:'',
			taskId:'',
			taskCode:'',
			hasCheckManage: false,
			isIncludeInvisible: '',
			taskCreateUser:'',
			checkDeptIds: [],
			searchParams:{},
			hadCreateOrgIds: [],
		}
	},
	async created() {
		//如果是通过跳转过来的，标签的名称设置为跳转后的标题
		let route = router.currentRoute.value;
		if (route.meta) {
			this.title = route.meta.title;
		}
		let routeParams = this.$store.state.routeParams[this.$route.params.key];
		if (routeParams) {
			if (routeParams.title) {
				useTabs.setTitle(routeParams.title);
				document.title = routeParams.title;
			}
			if (routeParams.fixedParams) {
				if (routeParams.fixedParams.taskId) {
					this.taskId = routeParams.fixedParams.taskId;
					this.fixedParams.taskId = routeParams.fixedParams.taskId;
				}
				if (routeParams.fixedParams.searchType) {
					this.fixedParams.searchType = routeParams.fixedParams.searchType;
				}
				if (routeParams.fixedParams.taskName) {
					this.taskName = routeParams.fixedParams.taskName;
				}
				if (routeParams.fixedParams.taskCode) {
					this.taskCode = routeParams.fixedParams.taskCode;
				}
				if (routeParams.fixedParams.taskCreateUser) {
					this.taskCreateUser = routeParams.fixedParams.taskCreateUser;
				}
				if (routeParams.fixedParams.isIncludeInvisible) {
					this.isIncludeInvisible = routeParams.fixedParams.isIncludeInvisible;
				}
				if (routeParams.fixedParams.taskStatus) {
					this.taskStatus = routeParams.fixedParams.taskStatus;
				}
				if (routeParams.fixedParams.isManage) {
					this.isManage = routeParams.fixedParams.isManage;
				}
			}
			if (routeParams.searchParams) {
				Object.assign(this.searchParams, routeParams.searchParams);
			}
		}
		if (this.taskStatus === "1") {
			let newButtons = []
			if(this.isIncludeInvisible === '0'){
				newButtons = [
					{name: "导出", icon: "el-icon-download", type: "info", click: "export", permission: ""},
					{name: "盘点报表", icon: "el-icon-download", type: "info", click: "exportTask", permission: ""},
					{name: "盘点报告", icon: "el-icon-download", type: "info", click: "checkReport", permission: "checkReport"},
				]
			}else{
				newButtons = [
					{name: "导出", icon: "el-icon-download", type: "info", click: "export", permission: ""},

					{name: "盘点报表", icon: "el-icon-download", type: "info", parent:true, permission: "",
						childrenbuttons:[
							{name: "账内", type: "info", click: "exportTask"},
							{name: "含账外", type: "info", click: "exportTask"},
						]
					},
					{name: "盘点报告", icon: "el-icon-download", type: "info",parent:true, permission: "checkReport",
						childrenbuttons:[
							{name: "账内", type: "info", click: "checkReport"},
							{name: "含账外", type: "info", click: "checkReportOut"},
						]
					},
				]
			}
			Object.assign(this.buttons, newButtons);
		} else {
			let newButtons = [];
			if (this.isIncludeInvisible === '0') {
				newButtons = [
					{name: this.$t('button.add'), icon: "el-icon-plus", click: "add", permission: "documentNew"},
					{
						name: this.$t('button.edit'),
						icon: "el-icon-edit",
						type: "info",
						click: "edit",
						permission: "documentEdit"
					},
					{
						name: this.$t('button.delete'),
						icon: "el-icon-delete",
						click: "delCheckDocument",
						type: "info",
						permission: "documentDel"
					},
					{name: "撤回", icon: "el-icon-edit", type: "info", click: "cancal", permission: "documentCancel"},
					{
						name: "变更管理人",
						icon: "el-icon-edit",
						type: "info",
						click: "changeCheckUser",
						permission: "checkManageUser"
					},
					{name: "导出", icon: "el-icon-download", type: "info", click: "export", permission: "export"},
					{name: "盘点处理", icon: "el-icon-plus", type: "info", click: "doCheck", permission: "doCheck"},
					{name: "盘点报表", icon: "el-icon-download", type: "info", click: "exportTask", permission: ""},
					{
						name: "盘点报告",
						icon: "el-icon-download",
						type: "info",
						click: "checkReport",
						permission: "checkReport"
					},
				]
			} else {
				newButtons = [
					{name: this.$t('button.add'), icon: "el-icon-plus", click: "add", permission: "documentNew"},
					{
						name: this.$t('button.edit'),
						icon: "el-icon-edit",
						type: "info",
						click: "edit",
						permission: "documentEdit"
					},
					{
						name: this.$t('button.delete'),
						icon: "el-icon-delete",
						click: "delCheckDocument",
						type: "info",
						permission: "documentDel"
					},
					{name: "撤回", icon: "el-icon-edit", type: "info", click: "cancal", permission: "documentCancel"},
					{
						name: "变更管理人",
						icon: "el-icon-edit",
						type: "info",
						click: "changeCheckUser",
						permission: "checkManageUser"
					},
					{name: "导出", icon: "el-icon-download", type: "info", click: "export", permission: "export"},
					{name: "盘点处理", icon: "el-icon-plus", type: "info", click: "doCheck", permission: "doCheck"},
					{name: "盘点报表", icon: "el-icon-download", parent: true, type: "info", permission: "",
						childrenbuttons:[
							{name: "账内", type: "info", click: "exportTask"},
							{name: "含账外", type: "info", click: "exportTask"},
						]
					},
					{
						name: "盘点报告",
						icon: "el-icon-download",
						type: "info",
						parent: true,
						permission: "checkReport",
						isParentBorder:true,
						childrenbuttons: [
							{name: "账内", type: "info", click: "checkReport"},
							{name: "含账外", type: "info", click: "checkReportOut"},
						]
					},
				]
			}
			Object.assign(this.buttons, newButtons);
		}
		this.fixedParams.queryUser = this.loginUser.id;
		this.fixedParams.readDeptIds = this.readDeptIds;
		let queryParams = {};
		if (routeParams) {
			Object.assign(queryParams, this.fixedParams);
		}
		await this.getCountData(queryParams);
		let queryDtoDept = {
			firstEntity: "FamsAssetCheckTask",
			firstEntityId: this.taskId,
			secondEntity: "ManageDept",
		};
		let deptRsp = await this.$API.system.relMap.load.post(queryDtoDept);
		if (deptRsp.code === 2000 && Array.isArray(deptRsp.data)) {
			deptRsp.data.forEach(item => {
				this.checkDeptIds.push(item.secondEntityId);
				if(this.readDeptIds.includes(item.secondEntityId)){
					this.hasCheckManage = true;
				}
			});
		}
		this.searches = [
			{type: "input", name: "盘点单编码", code: "code", placeholder: "请输入盘点单编码", maxlength: 30, showLimit: true},
			{type: "input", name: "盘点单名称", code: "name", placeholder: "请输入任务名称"},
			{type: "select", name: "任务类型", code: "taskType", placeholder: "请选择任务类型", dictCode:'TASK_TYPE'},
			// {type: "tree-select", name: "制定部门", code: "orgIds", placeholder: "请选择制定部门", dictCode:'SysOrganization',checkStrictly:true,multiple:true,dataPermissionProcess:true,priKey:true},
			{type: "tree-select", name: "盘点部门", code: "orgIds", placeholder: "请选择盘点部门", dictCode:'SysOrganization',checkStrictly:true,multiple:true,priKey:true,permissionData:this.checkDeptIds,dataPermissionProcess:true},
			// {type: "selector", name: "盘点管理员", code: "checkManageUser", placeholder: "请选择盘点管理员", dictCode:'SysUser',priKey:true},
			{type: "daterange", name: "制定日期", code: "createTimeStart,createTimeEnd", placeholder: "请选择制定日期", valueFormat:"YYYYMMDD" , formatter:"YYYY-MM-dd",range:365},
			{type: "daterange", name: "完成日期", code: "finishDateStart,finishDateEnd", placeholder: "请选择完成日期", valueFormat:"YYYYMMDD" , formatter:"YYYY-MM-dd",range:365},
		];
		this.isAlready = true;
	},
	beforeCreate(){
	},
	mounted() {
	},
	methods: {
		buttonHandler(index, name) {
			this.$options.methods[name](this, index);
		},
		async searchTreeHandler(data) {
			let queryParams = {pathCode:data.levelCode}
			this.parentLevelCode= data.levelCode;
			await this.$refs.table.refresh(queryParams);
		},
		//刷新页面
		refreshPageFun() {
			this.searchHandler();
			let queryParams = {};
			Object.assign(queryParams,this.fixedParams);
			this.getCountData(queryParams);
		},
		async getCountData(queryParams) {
			if (this.taskId) {
				let rsp = await this.$API.asset.checkDocumentApi.getCountByStatus.post(queryParams);
				if (rsp.code === 2000) {
					if (rsp.data != null) {
						let optionsData = [
							{
								label: "全部(" + rsp.data.totalCount + ")",
								value: ""
							},
							{
								label: "未盘(" + rsp.data.noDoCount + ")",
								value: "0"
							},
							{
								label: "盘点中(" + rsp.data.doingCount + ")",
								value: "1"
							},
							{
								label: "盘点结束(" + rsp.data.endCount + ")",
								value: "2"
							},
						];
						Object.assign(this.filterData[0].options, optionsData);
					}
				}
				let customCountRsp = await this.$API.asset.checkDocumentApi.customCountQueryWithWrapper.post(queryParams);
				if (customCountRsp.code === 2000) {
					if (customCountRsp.data != null) {
						let optionsData = [
							{
								label: "全部(" + customCountRsp.data.totalCount + ")",
								value: ""
							},
							{
								label: "未盘(" + customCountRsp.data.noDoCount + ")",
								value: "noDoCount"
							},
							{
								label: "正常(" + customCountRsp.data.normalCount + ")",
								value: "normalCount"
							},
							{
								label: "异常(" + customCountRsp.data.errCount + ")",
								value: "errCount"
							},
							{
								label: "盘盈(" + customCountRsp.data.surplusCount + ")",
								value: "surplusCount"
							},
							{
								label: "盘亏(" + customCountRsp.data.lossCount + ")",
								value: "lossCount"
							},
						];
						Object.assign(this.filterData[1].options, optionsData);
					}
				}
			}
		},

		async searchHandler() {
			let queryParams = {pathCode: this.parentLevelCode}
			queryParams.status = this.documentStatus;
			await this.$refs.table.refresh(queryParams);
		},
		columnClickHandler(name,data){
			this.$options.methods[name](this, data);
		},
		//添加
		add(_this) {
			if((_this.isManage === true && _this.hasCheckManage === true) || _this.taskCreateUser === _this.loginUser.id) { /* empty */ }else{
				_this.$message.error("您没有权限");
				return;
			}
			_this.searchCheckDocumentEdit(null,_this.taskId)
		},
		//导出
		async export(_this,index) {
			_this.$refs.button.loading(index,true);
			let queryPrams = {};
			queryPrams.status = _this.documentStatus;
			queryPrams.checkResult = _this.checkResult;
			queryPrams.readDeptIds = _this.readDeptIds;
			let exportApi = _this.$API.asset.checkDocumentApi.exportData;
			let exTableRef = _this.$refs.table;
			let exportBtnRef = _this.$refs.button;
			await BaseTemplate.export(_this, exportApi, queryPrams, exportBtnRef, index, exTableRef);
			_this.$refs.button.loading(index,false);
		},
		//导出任务下的所有盘点明细
		async exportTask(_this,index) {
			let selections = _this.$refs.table.selections();
			if(selections.length === 0){
				let title = '是否汇总全部盘点单报表?'
				if(this.isIncludeInvisible === '0'){
					title = '是否汇总全部盘点单账内报表?'
				}
				let confirm = await _this.$confirm(title, '提示', {type: 'warning'}).then(() => {return true;}).catch(() => {return false;});
				if (!confirm) return;
				_this.$refs.button.loading(index,true);
				let queryPrams = {taskId : _this.taskId};
				queryPrams.status = _this.documentStatus;
				queryPrams.checkResult = _this.checkResult;
				queryPrams.queryUser = _this.loginUser.id;
				queryPrams.exportType = 'checlDocumentExportDetail';
				queryPrams.exportName = "盘点任务"+_this.taskCode+'盘点单明细';
				if(this.isIncludeInvisible === '0'){
					queryPrams.assetType = 'in'
				}
				Object.assign(queryPrams, _this.$refs.table.queryParams());
				let res = await _this.$API.asset.checkDocumentApi.exportData.post(queryPrams);
				if (res.code === 2000) {
					await _this.$alert(_this.$t('common.export_request_success'), "提示", {type: 'success'}).catch(()=>{});
				}
				_this.$refs.button.loading(index,false);
			}else{
				_this.$refs.button.loading(index,true);
				var delarray = [];
				for (let index = 0; index < selections.length; index++) {
					const element = selections[index];
					delarray.push(element.id);
				}
				let queryPrams = {
					taskId : _this.taskId,
					ids : delarray,
					exportType: 'checlDocumentExportDetail',
				};
				if(this.isIncludeInvisible === '0'){
					queryPrams.assetType = 'in'
				}
				queryPrams.exportName = "盘点任务"+_this.taskCode+'盘点单明细';
				Object.assign(queryPrams, _this.$refs.table.queryParams());
				let res = await _this.$API.asset.checkDocumentApi.exportData.post(queryPrams);
				if (res.code === 2000) {
					await _this.$alert(_this.$t('common.export_request_success'), "提示", {type: 'success'}).catch(()=>{});
				}
				_this.$refs.button.loading(index,false);
			}

		},
		//编辑
		edit(_this) {

			let row = _this.$refs.table.selectionOne();
			if (!row) {
				return;
			}
			if(_this.taskStatus === "1"){
				_this.$message.warning("已结束的盘点任务的盘点单可以编辑");
				return;
			}
			if(row.status === "2"){
				_this.$message.warning("已盘点结束的盘点单无法编辑");
				return;
			}
			if(row.createUser === _this.loginUser.id || (_this.isManage === true && _this.hasCheckManage === true) || row.checkManageUser.includes(_this.loginUser.id) || _this.taskCreateUser === _this.loginUser.id){ /* empty */ }else{
				_this.$message.error("您没有权限");
				return;
			}
			// _this.$nextTick(() => {
			// 	_this.$refs.editDialog.open(row);
			// })
			_this.searchCheckDocumentEdit(row,_this.taskId);
		},
		//编辑
		editDetail(_this,row) {
			if(_this.taskStatus === "1"){
				_this.$message.warning("已盘点的盘点任务的盘点单可以编辑");
				return;
			}
			if(row.status === "2"){
				_this.$message.warning("已盘点结束的盘点单无法编辑");
				return;
			}
			if(row.createUser === _this.loginUser.id || row.checkManageUser.includes(_this.loginUser.id) || _this.taskCreateUser === _this.loginUser.id){ /* empty */ }else{
				_this.$message.warning("只能编辑自己管理范围内或自己创建的盘点单");
				return;
			}
			// _this.$nextTick(() => {
			// 	_this.$refs.editDialog.open(row);
			// })
			_this.searchCheckDocumentEdit(row,_this.taskId);
		},
		//盘点处理
		async doCheck(_this,index) {
			if(_this.taskStatus !== "0"){
				_this.$message.warning("只有进行中的盘点任务才能进行盘点处理");
				return;
			}
			let selections = _this.$refs.table.selections();
			let documentIds = '';
			if (selections.length !== 0) {
				let confirm = await _this.$confirm(`是否对选中的${selections.length}盘点单进行盘点处理?`, '提示', {type: 'warning'}).then(() => {return true;}).catch(() => {return false;});
				if (!confirm){
					_this.$refs.button.loading(index,false);
					return;
				}
				selections.forEach((row) => {
					if (_this.taskCreateUser === _this.loginUser.id || (_this.isManage === true && _this.readDeptIds.includes(row.orgId)) || row.createUser === _this.loginUser.id || row.checkManageUser.includes(_this.loginUser.id)) {
						if (documentIds) {
							documentIds += ',';
							documentIds += row.id;
						} else {
							documentIds = row.id;
						}
					}
				})
				if (!documentIds) {
					_this.$message.warning("您选择的盘点明细没有权限进行盘点处理");
					return;
				}
			}
			_this.$refs.button.loading(index,true);
			if (selections.length === 0) {
				let confirm = await _this.$confirm('是否汇总全部盘点单进行盘点处理?', '提示', {type: 'warning'}).then(() => {return true;}).catch(() => {return false;});
				if (!confirm){
					_this.$refs.button.loading(index,false);
					return;
				}
				let queryPrams = {taskId : _this.taskId};
				queryPrams.status = _this.documentStatus;
				queryPrams.checkResult = _this.checkResult;
				queryPrams.queryUser = _this.loginUser.id;
				queryPrams.isManage = '1';
				Object.assign(queryPrams, _this.$refs.table.queryParams());
				queryPrams.searchType = '';
				let resp = await _this.$API.asset.checkDocumentApi.getIdByQuery.post(queryPrams);
				if(resp.code === 2000){
					if(resp.data && resp.data.length > 0){
						documentIds = resp.data.join(',');
					}else{
						_this.$refs.button.loading(index,false);
						_this.$message.warning("只能对自己管理范围内或自己创建的盘点单进行处理");
						return;
					}
				}else{
					this.$message.warning("系统繁忙，请重新操作");
				}
				_this.$refs.button.loading(index,false);
				_this.$router.push({
					name: "checkDoPrepare",
					params: {
						fromRouteId: _this.$TOOL.crypto.MD5(_this.$route.path),
						documentIds: documentIds,
						taskId: _this.taskId
					}
				});
			} else {
				_this.$refs.button.loading(index,false);
				_this.$router.push({
					name: "checkDoPrepare",
					params: {
						fromRouteId: _this.$TOOL.crypto.MD5(_this.$route.path),
						documentIds: documentIds,
						taskId: _this.taskId
					}
				});
			}

		},
		//变更管理员
		changeCheckUser(_this){
			let row = _this.$refs.table.selectionOne();
			if (!row) {
				return;
			}
			let entity = {
				checkManageUsers: [],
				documentId: row.id,
				orgId: row.orgId,
			}
			if(_this.taskCreateUser === _this.loginUser.id || (_this.isManage === true && _this.readDeptIds.includes(row.orgId)) || row.createUser === _this.loginUser.id || row.checkManageUser.includes(_this.loginUser.id)){
				//满足即可操作
			}else{
				_this.$message.warning("只能变更自己管理范围内或自己创建的盘点单");
				return;
			}

			if(row.checkManageUser){
				entity.checkManageUsers = row.checkManageUser;
			}

			_this.$refs.changeCheckUser.open(entity);
		},
		//撤回
		async cancal(_this, index) {
			let row = _this.$refs.table.selectionOne();
			if (!row) {
				return;
			}
			if (row.status !== "2") {
				_this.$message.warning("该盘点单未结束")
				return;
			}
			if (_this.taskCreateUser === _this.loginUser.id || (_this.isManage === true && _this.readDeptIds.includes(row.orgId)) || row.createUser === _this.loginUser.id || row.checkManageUser.includes(_this.loginUser.id)) {
				//满足即可操作
			} else {
				_this.$message.warning("只能撤销自己管理范围内或自己创建的盘点单");
				return;
			}
			_this.$refs.button.loading(index, true);
			let rsp = await _this.$API.asset.checkDocumentApi.cancle.post({id: row.id, taskId: row.taskId});
			if (rsp.code === 2000) {
				_this.$message.success(_this.$t("code." + rsp.code));
				_this.refreshPageFun();
			} else {
				_this.$message.warning(rsp.message)
			}
			_this.$refs.button.loading(index, false);

		},
		//查看
		show(_this) {
			let row = _this.$refs.table.selectionOne();
			if (!row) {
				return;
			}
			_this.$nextTick(() => {
				_this.$refs.viewDialog.open(row);
			})
		},
		//查看
		async show1(_this, row) {
			_this.searchCheckDocumentDetail(row,_this.taskId);
		},
		searchCheckDocumentDetail(checkDocumentData,taskId) {
			let title = "盘点单"+checkDocumentData.code+"盘点单明细";
			//跳转到搜索台账页面
			let fromRouteId = this.$TOOL.crypto.MD5(this.$route.path);//当前页面的路由地址
			let key = this.$TOOL.crypto.MD5(checkDocumentData.code);//可以做为key的关键字段或内容
			//设置搜索参数
			let routeParams = {
				id: key,
				title: title,
				fixedParams:{
					taskId:taskId,
					documentId:checkDocumentData.id,
				},//固定搜索参数，打开页面后，用户通过搜索界面的清空按钮无法清除
			};
			this.$store.dispatch("addRouteParams", routeParams);
			this.$router.push({
				name: "toCheckDocumentDetail",
				params: {fromRouteId: fromRouteId, key: key}
			});
		},
		searchCheckDocumentEdit(checkDocumentData,taskId) {
			let title = '';
			if(checkDocumentData){
				title = "编辑"+checkDocumentData.code+"盘点单";
			}else{
				title = "新增盘点单";
			}
			//跳转到搜索台账页面
			let fromRouteId = this.$TOOL.crypto.MD5(this.$route.path);//当前页面的路由地址
			let key = '';
			if(checkDocumentData){
				key = this.$TOOL.crypto.MD5(checkDocumentData.code);//可以做为key的关键字段或内容
			}else{
				key = this.$TOOL.crypto.MD5(taskId+uuid("s"));//可以做为key的关键字段或内容
			}
			//设置搜索参数
			let routeParams = {
				id: key,
				title: title,
				fixedParams:{
				},//固定搜索参数，打开页面后，用户通过搜索界面的清空按钮无法清除
			};
			if(checkDocumentData){
				routeParams.fixedParams = {
					taskId:taskId,
					documentId:checkDocumentData.id,
				}
			}else{
				routeParams.fixedParams = {
					taskId:taskId,
				}
			}
			routeParams.fixedParams.searchType = this.fixedParams.searchType
			this.$store.dispatch("addRouteParams", routeParams);
			this.$router.push({
				name: "toCheckDocumentAdd",
				params: {fromRouteId: fromRouteId, key: key}
			});
		},
		//盘点报告
		async checkReport(_this,index) {
			let selections = _this.$refs.table.selections();
			let documentIds = [];
			if (selections.length !== 0) {
				selections.forEach((row) => {
					if (_this.taskCreateUser === _this.loginUser.id || (_this.isManage === true && _this.readDeptIds.includes(row.orgId)) || row.createUser === _this.loginUser.id || row.checkManageUser.includes(_this.loginUser.id)) {
						documentIds.push(row.id)
					}
				})
				if(documentIds.length === 0){
					_this.$message.warning("只能生成自己管理范围内或自己创建的盘点单的盘点报告");
					return;
				}
			}else{
				let confirm = await _this.$confirm('是否汇总全部盘点单账内报告?', '提示', {type: 'warning'}).then(() => {return true;}).catch(() => {return false;});
				if (!confirm){
					return;
				}
				_this.$refs.button.loading(index, true);
				let queryPrams = {taskId : _this.taskId};
				queryPrams.status = _this.documentStatus;
				queryPrams.checkResult = _this.checkResult;
				queryPrams.queryUser = _this.loginUser.id;
				Object.assign(queryPrams, _this.$refs.table.queryParams());
				queryPrams.searchType = '';
				let resp = await _this.$API.asset.checkDocumentApi.getIdByQuery.post(queryPrams);
				if(resp.code === 2000){
					if(resp.data && resp.data.length > 0){
						documentIds = resp.data;
					}else{
						_this.$refs.button.loading(index, false);
						_this.$message.warning("只能对自己管理范围内或自己创建的盘点单生成盘点报告");
						return;
					}
				}else{
					_this.$refs.button.loading(index, false);
					_this.$message.warning("系统繁忙，请重新操作");
					return;
				}
			}
			let queryPrams = {};
			_this.searchCheckReport(queryPrams,_this.taskId,documentIds,_this.taskCode);

		},
		searchCheckReport(queryPrams,taskId,documentIds,taskCode) {
			let title = '盘点任务'+taskCode+"下盘点单报告";
			//跳转到搜索台账页面
			let fromRouteId = this.$TOOL.crypto.MD5(this.$route.path);//当前页面的路由地址
			let key = '';
			key = this.$TOOL.crypto.MD5(taskId+uuid("s"));
			//设置搜索参数
			let routeParams = {
				id: key,
				title: title,
				fixedParams:{
				},//固定搜索参数，打开页面后，用户通过搜索界面的清空按钮无法清除
				searchParams:{},
			};
			if(documentIds.length > 0){
				routeParams.fixedParams = {
					taskId:taskId,
					ids:documentIds,
					taskCode:taskCode,
				}
			}else{
				routeParams.fixedParams = {
					taskId:taskId,
					taskCode:taskCode,
				}
				routeParams.searchParams = queryPrams;
			}
			this.$store.dispatch("addRouteParams", routeParams);
			this.$router.push({
				name: "toCheckReport",
				params: {fromRouteId: fromRouteId, key: key}
			});
		},
		//盘点报告(包含账外)
		async checkReportOut(_this,index) {
			let selections = _this.$refs.table.selections();
			let documentIds = [];
			if (selections.length !== 0) {
				selections.forEach((row) => {
					if (_this.taskCreateUser === _this.loginUser.id || row.createUser === _this.loginUser.id || (_this.readDeptIds.includes(row.orgId) && _this.isManage === true) || row.checkManageUser.includes(_this.loginUser.id)) {
						documentIds.push(row.id)
					}
				})
				if(documentIds.length === 0){
					_this.$message.warning("只能生成自己管理范围内或自己创建的盘点单的盘点报告");
					return;
				}
			}else{
				let confirm = await _this.$confirm('是否汇总全部盘点单报告?', '提示', {type: 'warning'}).then(() => {return true;}).catch(() => {return false;});
				if (!confirm){
					return;
				}
				_this.$refs.button.loading(index, true);
				let queryPrams = {taskId : _this.taskId};
				queryPrams.status = _this.documentStatus;
				queryPrams.checkResult = _this.checkResult;
				queryPrams.queryUser = _this.loginUser.id;
				Object.assign(queryPrams, _this.$refs.table.queryParams());
				queryPrams.searchType = '';
				let resp = await _this.$API.asset.checkDocumentApi.getIdByQuery.post(queryPrams);
				if(resp.code === 2000){
					if(resp.data && resp.data.length > 0){
						documentIds = resp.data;
					}else{
						_this.$refs.button.loading(index, false);
						_this.$message.warning("只能对自己管理范围内或自己创建的盘点单生成盘点报告");
						return;
					}
				}else{
					_this.$refs.button.loading(index, false);
					_this.$message.warning("系统繁忙，请重新操作");
					return;
				}
			}
			let queryPrams = {};
			_this.searchCheckReportOut(queryPrams,_this.taskId,documentIds,_this.taskCode);

		},
		searchCheckReportOut(queryPrams,taskId,documentIds,taskCode) {
			let title = '盘点任务'+taskCode+"下盘点单报告";
			//跳转到搜索台账页面
			let fromRouteId = this.$TOOL.crypto.MD5(this.$route.path);//当前页面的路由地址
			let key = '';
			key = this.$TOOL.crypto.MD5(taskId+uuid("s"));
			//设置搜索参数
			let routeParams = {
				id: key,
				title: title,
				fixedParams:{
				},//固定搜索参数，打开页面后，用户通过搜索界面的清空按钮无法清除
				searchParams:{},
			};
			if(documentIds.length > 0){
				routeParams.fixedParams = {
					taskId:taskId,
					ids:documentIds,
					taskCode:taskCode,
				}
			}else{
				routeParams.fixedParams = {
					taskId:taskId,
					taskCode:taskCode,
				}
				routeParams.searchParams = queryPrams;
			}
			this.$store.dispatch("addRouteParams", routeParams);
			this.$router.push({
				name: "toCheckReportOut",
				params: {fromRouteId: fromRouteId, key: key}
			});
		},
		//批量删除
		async delCheckDocument(_this, index) {
			let selections = _this.$refs.table.selections();
			if (selections.length !== 0) {
				_this.$confirm(`确定删除选中的 ${selections.length} 项盘点单吗？如果盘点单含有盘点明细将会被一并删除`, '警告', {
					type: 'warning'
				}).then(async () => {
					_this.$refs.button.loading(index, true);
					let delarray = [];
					for (let index = 0; index < selections.length; index++) {
						let row = selections[index];
						if(_this.taskCreateUser === _this.loginUser.id || (_this.readDeptIds.includes(row.orgId) && _this.isManage === true) || row.createUser === _this.loginUser.id || row.checkManageUser.includes(_this.loginUser.id)){
							//满足即可操作
							delarray.push(row.id);
						}
					}
					if(delarray.length === 0){
						_this.$refs.button.loading(index, false);
						_this.$message.warning("只能删除自己管理范围内或自己创建的盘点单");
						return;
					}
					let res = await _this.$API.asset.checkDocumentApi.deleteByIds.post(delarray);
					if (res.code === 2000) {
						_this.$message.success(_this.$t("code."+res.code));
						useTabs.refresh();
					}
					_this.$refs.button.loading(index, false);
				}).catch(() => {
					_this.$refs.button.loading(index, false);
				});
			}else{
				let confirm = await _this.$confirm('确定删除所有盘点单项吗？如果盘点单含有盘点明细将会被一并删除', '警告', {type: 'warning'}).then(() => {return true;}).catch(() => {return false;});
				if (!confirm){
					return;
				}
				let queryPrams = {taskId : _this.taskId};
				Object.assign(queryPrams, _this.$refs.table.queryParams())
				queryPrams.status = _this.documentStatus;
				queryPrams.checkResult = _this.checkResult;
				queryPrams.queryUser = _this.loginUser.id;
				queryPrams.isManage = '1';
				queryPrams.searchType = '';
				let res = await _this.$API.asset.checkDocumentApi.deleteByQuery.post(queryPrams);
				if (res.code === 2000) {
					_this.$message.success(_this.$t("code."+res.code));
					useTabs.refresh();
				}
				_this.$refs.button.loading(index, false);
			}
		},
		//标签切换
		async tabChange(name){
			this.documentStatus = name.status;
			this.checkResult = name.checkResult;
			await this.$refs.table.refresh(name);
		},
	}
}

</script>
<style scoped>

</style>
